<template>
	<view class="dispatch-order">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
			<uni-row>
				<uni-col :span="15">
					<uni-forms-item label="服务单号">
						<uni-easyinput :styles="inputStyles" :disabled="true" v-model="orderSn"
							type="text"></uni-easyinput>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="9">
					<uni-forms-item label="派单人">
						<uni-easyinput :styles="inputStyles" :disabled="true" v-model="username"></uni-easyinput>
					</uni-forms-item>
				</uni-col>
			</uni-row>
			<!-- 服务类型 -->
			<uni-forms-item label="服务类型">
				<uni-row>
					<uni-col :span="16">
						<uni-easyinput :styles="inputStyles" type="text" :disabled="true" border="none"
							v-model="formData.service_name" />
					</uni-col>
					<uni-col :span="8">
						<button v-if="formData.customer_location" type="primary" size="mini"
							@click="openNavigation(formData.customer_location)" icon="map" shape="circle">客户位置</button>
						<button type="success" size="mini" @click="makeCall(formData.customer_phone)" icon="phone"
							shape="circle">联系客户</button>
					</uni-col>
				</uni-row>
			</uni-forms-item>
			<!-- 客户需求 -->
			<uni-forms-item label="客户需求" name="customer_needs">
				<uni-easyinput :styles="inputStyles" :autoHeight="true" v-model="formData.customer_needs"
					:maxlength="200" placeholder="请输入客户需求" type="textarea"></uni-easyinput>
			</uni-forms-item>
			<!-- 负责人 -->
			<uni-forms-item label="车管家" name="butler_id">
				<uni-data-picker v-model="formData.butler_id" :localdata="butlerList"
					placeholder="选择车管家"></uni-data-picker>
			</uni-forms-item>
			<!-- 联盟点 -->
			<uni-forms-item label="宇壹联盟" name="store_id">
				<uni-data-picker v-model="formData.store_id" :localdata="storeList"
					placeholder="选择宇壹联盟门店"></uni-data-picker>
			</uni-forms-item>

			<!-- 客户需求 -->
			<uni-forms-item label="备注" name="service_content">
				<uni-easyinput :styles="inputStyles" :autoHeight="true" v-model="formData.service_content"
					:maxlength="128" placeholder="请输入服务内容" type="text"></uni-easyinput>
			</uni-forms-item>

			<!-- 协议价 -->
			<uni-forms-item label="协议价" name="price">
				<uni-easyinput :styles="inputStyles" placeholder="填写协议价" type="digit" v-model.number="formData.price"
					@change="priceChange"></uni-easyinput>
				<button v-if="formData.customer_location" type="primary" size="mini" icon="map"
					shape="circle">查看工单明细</button>
			</uni-forms-item>

			<!-- 车管家收益 -->
			<uni-forms-item label="车管家收益" name="butler_income">
				<uni-easyinput :styles="inputStyles" v-model="formData.butler_income" :disabled="true"
					type="digit"></uni-easyinput>
			</uni-forms-item>
		</uni-forms>

		<view class="button-group">
			<button type="primary" @click="submit">审核通过，立即派单</button>
		</view>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/yycw_car_service_order.js'
	import {
		cal
	} from '@/utils/cal'
	const userInfo = uniCloud.getCurrentUserInfo()
	const db = uniCloud.database()
	const dbCollectionName = 'yycw_car_service_order'

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				customer_needs: '',
				service_content: '',
				store_id: '',
				user_id: '67dee5232eea6559d2297af7',
				butler_id: '67dee5232eea6559d2297af7',
				supervisor_id: '',
				price: 0.0,
				butler_income: 0.0
			}
			return {
				formData,
				orderSn: '',
				username: '',
				storeList: [],
				butlerList: [],
				supervisorList: [],
				orderId: '',
				inputStyles: {
					color: '#000000',
					disableColor: '#ffffff'
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			if (e.id) {
				this.orderId = e.id
				this.getDetail(e.id)
				this.getDatas()

			} else {
				uni.showToast({
					title: '缺少订单信息',
					icon: 'fail'
				})
				uni.navigateBack()
			}

		},
		methods: {
			priceChange() {
				if (this.formData.company_fee > 0) {
					this.formData.butler_income = cal.sub(this.formData.price, this.formData.company_fee)
				} else if (this.formData.company_fee_rate > 0) {
					this.formData.butler_income = cal.mul(this.formData.price, cal.sub(1, this.formData.company_fee_rate))
				}
			},
			makeCall(phone) {
				uni.makePhoneCall({
					phoneNumber: phone
				});
			},
			openNavigation(location) {
				uni.openLocation({
					latitude: Number(location?.latitude),
					longitude: Number(location?.longitude),
					name: location?.name
				});
			},
			async getDatas() {
				try {
					// 获取车管家列表
					const butlerRes = await db.collection('uni-id-users')
						.where({
							role: 'butler',
							status: 0
						})
						.field('nickname as text, _id as value')
						.get()

					this.butlerList = butlerRes.result.data

					const storeRes = await db.collection('yycw_store').field('_id as value,store_name as text').get()
					this.storeList = storeRes.result.data

				} catch (e) {
					console.error('获取数据失败:', e)
					uni.showToast({
						icon: 'error',
						title: '获取数据失败'
					})
				}
			},
			async getDetail(id) {
				try {
					const orderRes = await db.collection(dbCollectionName)
						.where({
							_id: id
						})
						.field(`
						type_id,
						order_sn,
						customer_needs,
						customer_phone,
						customer_location,
						store_id,
						offer_price,
						user_id,
						butler_id
						`) // 精准字段控制
						.getTemp()
					const tpyeTemp = await db.collection('yycw_car_service_type')
						.field(`
						_id,service_name,company_fee,company_fee_rate
						`) // 精准字段控制
						.getTemp()
					const detailRes = await db.collection(orderRes, tpyeTemp).get()
					if (detailRes.result.data && detailRes.result.data.length > 0) {
						const order = detailRes.result.data[0];
						// 步骤3：扁平化数据结构（避免嵌套）
						// console.debug('user_id:' + order.user_id)
						this.formData = {
							// 主表字段
							customer_needs: order.customer_needs || '',
							customer_phone: order.customer_phone || '',
							customer_location: order.customer_location,
							// offer_price: order.offer_price || 0,
							butler_id: order.butler_id || '',
							supervisor_id: order.supervisor_id || '',
							price: order.price || 0,
							butler_income: order.butler_income || 0,
							store_id: order.store_id || '',
							user_id: order.user_id,

							// 联表字段（服务类型）
							service_name: order.type_id[0]?.service_name || '',
							company_fee: order.type_id[0]?.company_fee || 0,
							company_fee_rate: order.type_id[0]?.company_fee_rate || 0,

						}
						this.orderSn = order.order_sn
						const {
							result
						} = await db.collection('uni-id-users').doc(order.user_id).field('_id,nickname').get()
						this.username = result.data[0]?.nickname || '未设置'
					}
				} catch (e) {
					console.error('获取订单详情失败:', e)
					uni.showToast({
						title: '查询订单失败',
						icon: 'none'
					})
				}
			},
			/**
			 * 验证表单并提交
			 */
			async submit() {
				if (this.formData.price <= 0) {
					uni.showToast({
						title: '请填写协议价格',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					mask: true
				})

				this.$refs.form.validate().then((res) => {
					const payload = {
						...res,
						status: 1,
						auditor_id: userInfo.uid,
						"dates": {
							"price_audit": new Date()
						},
					}
					return this.submitForm(payload)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.orderId).update(value).then((res) => {
					uni.showToast({
						icon: 'none',
						title: '报价审核成功',
						complete() {
							uni.navigateBack()
						}
					})
					// this.getOpenerEventChannel().emit('refreshData')
					// uni.navigateBack()
					// setTimeout(() => uni.navigateBack({
					// 	url: '/pages/yycw_car_service_order/serviceList?role=auditor'
					// }), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
		}
	}
</script>

<style lang="scss">
	.dispatch-order {
		padding: 20rpx;

		.button-group {
			margin-top: 30rpx;
			text-align: center;
		}
	}

	.is-disabled {
		color: #1e1e1e99 !important;
	}
</style>